from django.contrib import admin
from xtattend.models import *
from utils.excel import export_excel
import datetime


@admin.register(AttendanceManage)
class AttendanceAdmin(admin.ModelAdmin):
    list_display = ('项目名称', '姓名', '工号', 'hw_headman', 'hw_pm', 'reason', 'start_time', 'end_time', 'weekday', '角色', 'creator', 'create_time')

    date_hierarchy = 'start_time'
    list_per_page = 20
    list_filter = ('project', 'applicant__first_name')

    def 项目名称(self, obj):
        return obj.project.project_name

    def 姓名(self, obj):
        return obj.applicant.first_name

    def 工号(self, obj):
        return obj.applicant.username

    def 角色(self, obj):
        return obj.applicant.profile.role

    def save_execl(self, request, queryset):
        filename = 'media/{0}_{1}.xls'.format('Attendance', datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
        headers = [
            '序号', '归属项目', '姓名', '工号', '华为组长', '华为PM', '加班事由', '加班开始时间', '加班结束时间', '星期', '角色']
        columns = [
            'id', 'project__project_name', 'applicant__first_name', 'applicant__username', 'hw_headman',
            'hw_pm', 'reason', 'start_time', 'end_time', 'weekday', '角色']
        return export_excel(queryset, headers, columns, filename)

    save_execl.short_description = "导出Excel"

    actions = [save_execl]

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if not request.user.is_superuser and db_field.name == 'applicant':
            kwargs['initial'] = request.user.id
            kwargs['queryset'] = User.objects.filter(username=request.user.username)
        if db_field.name == 'creator':
            kwargs['initial'] = request.user.id
            kwargs['queryset'] = User.objects.filter(username=request.user.username)
        return super(AttendanceAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

    def get_queryset(self, request):
        """函数作用：使当前登录的用户只能看到自己负责的服务器"""
        qs = super(AttendanceAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(creator=request.user)





